﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Global
{
    /// <summary>
    /// 标记需要自动注册的服务类
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public class InjectableAttribute : Attribute
    {
        /// <summary>
        /// 服务生命周期类型
        /// </summary>
        public LifeTime LifeTime { get; }

        /// <summary>
        /// 指定服务接口类型（默认使用实现类的所有接口）
        /// </summary>
        public Type ServiceType { get; }

        /// <summary>
        /// 基本构造函数
        /// </summary>
        public InjectableAttribute() : this(LifeTime.Transient) { }

        /// <summary>
        /// 指定生命周期的构造函数
        /// </summary>
        /// <param name="lifeTime">服务生命周期</param>
        public InjectableAttribute(LifeTime lifeTime)
        {
            LifeTime = lifeTime;
        }

        /// <summary>
        /// 指定服务接口的构造函数
        /// </summary>
        /// <param name="serviceType">服务接口类型</param>
        public InjectableAttribute(Type serviceType) : this(serviceType, LifeTime.Transient) { }

        /// <summary>
        /// 完整参数构造函数
        /// </summary>
        /// <param name="serviceType">服务接口类型</param>
        /// <param name="lifeTime">服务生命周期</param>
        public InjectableAttribute(Type serviceType, LifeTime lifeTime)
        {
            ServiceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType));
            LifeTime = lifeTime;

            if (!serviceType.IsInterface)
                throw new ArgumentException("ServiceType must be an interface", nameof(serviceType));
        }
    }

    /// <summary>
    /// 服务生命周期枚举
    /// </summary>
    public enum LifeTime
    {
        /// <summary>
        /// 每次请求创建新实例
        /// </summary>
        Transient,

        /// <summary>
        /// 整个应用生命周期内单例
        /// </summary>
        Singleton,

        /// <summary>
        /// 每个作用域内单例
        /// </summary>
        Scoped
    }
}
